from django.shortcuts import render
from django.db.models import FilteredRelation,Q
from .models import Book
import platform
import django
from django.db import connection
import logging


def get_system_info():
    """获取系统信息的通用函数"""
    return {
        'django_version': django.get_version(),
        'database_info': connection.vendor,
        'os_info': f"{platform.system()} {platform.release()}",
    }

def annotate_and_select_related(request):
    used_method = 'annotate+select_related'
    context = get_system_info()
    annotate_input = request.GET.get('annotate_search', 'contact')
    alias_input = request.GET.get('alias', '')
    results = None
    debug_info = {}
    error=None
    try:
        # 漏洞代码
        qs = Book.objects.annotate(**{
                annotate_input: FilteredRelation("contact"),
            })
        filtered_relations = getattr(qs.query, '_filtered_relations', {})
        qs=qs.select_related(annotate_input)
        debug_info['method'] = used_method
        debug_info['query_sql'] = str(qs.query)
        debug_info['filtered_relations'] = str(filtered_relations)
        qs._fetch_all()
        results = qs
    except Exception as e:
        error = str(e)
        logging.error(f"Error in annotate_and_select_related: {error}")

    context.update({
        'annotate_input': annotate_input,
        'alias_input': alias_input,
        'results': results,
        'error': error,
        'used_method': used_method,
        'debug_info': debug_info
    })
    return render(request, 'vul_app/index.html', context)

def alias_and_order_by(request):
    context = get_system_info()
    alias_input = request.GET.get('alias', 'contact')
    debug_info = {}
    filtered_relations = {}
    used_method = 'alias+order_by'
    error=None
    results = None
    try:
        # 漏洞代码
        qs = Book.objects.alias(
            **{alias_input: FilteredRelation("contact")}
            )
        filtered_relations = getattr(qs.query, '_filtered_relations', {})
        qs = qs.order_by(alias_input)
        debug_info['method'] =used_method
        debug_info['query_sql'] = str(qs.query)
        debug_info['filtered_relations'] = str(filtered_relations)
        qs._fetch_all()
        results = qs
    except Exception as e:
        debug_info['error'] = str(e)
        logging.error(f"Error in alias_and_order_by: {e}")

    context.update({
        'alias_input': alias_input,
        'results': results,
        'error': error,
        'used_method': used_method,
        'debug_info': debug_info
    })
    return render(request, 'vul_app/index.html', context)

def alias_and_select_related(request):
    context = get_system_info()
    alias_input = request.GET.get('alias', 'contact')
    debug_info = {}
    filtered_relations = {}
    used_method = 'alias+select_related'
    error=None
    results = None
    try:
        # 漏洞代码
        qs = Book.objects.alias(**{alias_input: FilteredRelation("contact")})
        filtered_relations = getattr(qs.query, '_filtered_relations', {})

        qs = qs.select_related(alias_input)
        debug_info['method'] = used_method
        debug_info['query_sql'] = str(qs.query)
        debug_info['filtered_relations'] = str(filtered_relations)
        qs._fetch_all()
        results = qs
    except Exception as e:
        debug_info['error'] = str(e)
        logging.error(f"Error in alias_and_select_related: {e}")

    context.update({
        'alias_input': alias_input,
        'results': results,
        'error': error,
        'used_method': used_method,
        'debug_info': debug_info
    })
    return render(request, 'vul_app/index.html', context)
